package org.javaongems.client.vcl;

import com.google.gwt.json.client.JSONArray;
import com.google.gwt.json.client.JSONBoolean;
import com.google.gwt.json.client.JSONNull;
import com.google.gwt.json.client.JSONNumber;
import com.google.gwt.json.client.JSONObject;
import com.google.gwt.json.client.JSONString;

public class JsonComponentWriter implements ComponentWriter {
	protected JSONArray store = new JSONArray();
	protected int indexPos = 0;
	
	public void writeRootContainer(Container src) {
		src.writeState(this);
	}
	
	public void writeNumber(double val) {
		store.set(indexPos++, new JSONNumber(val));
	}
	
	public void writeBoolean(boolean val) {
		store.set(indexPos++, JSONBoolean.getInstance(val));
	}
	
	public void writeString(String val) {
		store.set(indexPos++, new JSONString(val));
	}
	
	public void writeNull() {
		store.set(indexPos++, JSONNull.getInstance());
	}
	
	public PropertiesWriter writeProperties() {
		JsonPropertiesWriter pw = new JsonPropertiesWriter();
		store.set(indexPos++, pw.properties);
		return pw;
	}
	
	public void writeComponent(Component child) {
		JsonComponentWriter childWrtr = new JsonComponentWriter();
		store.set(indexPos++, childWrtr.store);
		child.writeState(childWrtr);
	}
	
	public String toString() {
		return store.toString();
	}
	
	static public class JsonPropertiesWriter implements PropertiesWriter {
		protected JSONObject properties = new JSONObject();
		
		public void writeNumber(String name, double val) {
			JSONNumber propVal = new JSONNumber(val);
			properties.put(name, propVal);
		}

		public void writeBoolean(String name, boolean val) {
			JSONBoolean propVal = JSONBoolean.getInstance(val);
			properties.put(name, propVal);
		}

		public void writeString(String name, String val) {
			JSONString propVal = new JSONString(val);
			properties.put(name, propVal);
		}

		public void writeNull(String name) {
			properties.put(name, JSONNull.getInstance());
		}

		public PropertiesWriter writeNamedProperties(String name) {
			JsonPropertiesWriter pw = new JsonPropertiesWriter();
			properties.put(name, pw.properties);
			return pw;
		}
	}
}
